package com.sjz.han.industry.utils;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.NumberPicker;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
    private static Calendar calendar = Calendar.getInstance();
    private static String timeStr;
    static DatePickerDialog dialog = null;

    /**
     * type=1 年月日
     * type=2 年月
     *
     * @param context
     * @param handler
     * @param type
     */
    public static void showDateDialog(Context context, final Handler handler, final int type) {

        DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int mYear, int mMonth,
                                  int mDay) {
            }
        };
        /**
         * in a fullscreen DatePicker is the choice of parent theme:
         * 主题（不设置的话就是默认的 ，xiaomi mi 3c 是6.0系统，显示的就是日历样式的）
         * 设置方法是 AlertDialog.THEME_HOLO_LIGHT,
         * 直接new就可以了         DatePickerDialog(Context context, int themeResId, DatePickerDialog.OnDateSetListener listener, int year, int monthOfYear, int dayOfMonth)
         ** @deprecated *//*
    @Deprecated
    public static final int THEME_DEVICE_DEFAULT_DARK = 4;
    *//** @deprecated *//*
    @Deprecated
    public static final int THEME_DEVICE_DEFAULT_LIGHT = 5;
    *//** @deprecated *//*
    @Deprecated
    public static final int THEME_HOLO_DARK = 2;
    *//** @deprecated *//*
    @Deprecated
    public static final int THEME_HOLO_LIGHT = 3;
    *//** @deprecated *//*
    @Deprecated
    public static final int THEME_TRADITIONAL = 1;
*/

        dialog = new DatePickerDialog(context, AlertDialog.THEME_HOLO_LIGHT, dateListener,
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));

        //手动设置按钮
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "完成", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogs, int which) {
                //通过mDialog.getDatePicker()获得dialog上的DatePicker组件，然后可以获取日期信息
                DatePicker datePicker = dialog.getDatePicker();
                int year = datePicker.getYear();
                int month = datePicker.getMonth();
                int day = datePicker.getDayOfMonth();
//                if (type == 1) {
//                    timeStr = year + "-" + ((month + 1) < 10 ? "0" + (month + 1)
//                            : (month + 1)) + "-" + (day < 10 ? "0" + day
//                            : day);
//                } else if (type == 2) {
//                    timeStr = year + "年" + ((month + 1) < 10 ? "0" + (month + 1)
//                            : (month + 1)) + "月";
//                }

                timeStr = year + "-" + ((month + 1) < 10 ? "0" + (month + 1)
                        : (month + 1)) + "-" + (day < 10 ? "0" + day
                        : day);

                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("time", timeStr.toString());
//                bundle.putString("year", year + "");
//                bundle.putString("month", (month + 1) + "");
//                MyLog.e("时间选择："+timeStr.toString() );
                msg.what = type;
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.out.println("cancel~~cancel~~");
                dialog.cancel();
            }
        });
        dialog.show();
////     隐藏日   如果想隐藏年，把getChildAt(2)改为getChildAt(0) 此方法不兼容6.0
//        DatePicker dp = findDatePicker((ViewGroup) dialog.getWindow().getDecorView());
//        if (dp != null) {
//            ((ViewGroup) ((ViewGroup) dp.getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
//        }
    }

    /* 隐藏DatePicker中的日期
    * @param customDialog
    */
    private static void hideDatePickerDay(DatePickerDialog customDialog) {
        ViewGroup group = ((ViewGroup) ((ViewGroup) customDialog.getDatePicker().getChildAt(0))
                .getChildAt(0));
        boolean bool = false;
        for (int i = 0; i < group.getChildCount(); i++) {
            View view = group.getChildAt(i);
            String viewName = view.getClass().getName();
            if (bool) {
                view.setVisibility(View.GONE);
                continue;
            }
            if (view instanceof NumberPicker) {
                int maxNum = ((NumberPicker) view).getMaxValue();
                if (maxNum == 11) bool = true;
            }
        }
    }

    /**
     * 从当前Dialog中查找DatePicker子控件
     *
     * @param group
     * @return
     */
    private static DatePicker findDatePicker(ViewGroup group) {
        if (group != null) {
            for (int i = 0, j = group.getChildCount(); i < j; i++) {
                View child = group.getChildAt(i);
                if (child instanceof DatePicker) {
                    return (DatePicker) child;
                } else if (child instanceof ViewGroup) {
                    DatePicker result = findDatePicker((ViewGroup) child);
                    if (result != null)
                        return result;
                }
            }
        }
        return null;
    }

    public static Calendar DateToCalendar(Date date) {

        Calendar startdate = Calendar.getInstance();
        startdate.setTime(date);

        return startdate;
    }

    public static Date StringToDate(String String) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time = null;
        try {
            time = format.parse(String);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    public static String StringToDateZ(String string) {
//        MyLog.e("--------" + string);
        if (string == null || string.equals("")) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date time = null;
        try {
            time = format.parse(string);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return format.format(time);
    }

    public static String StringToDateT(String string) {
//        MyLog.e("--------" + string);
        if (string == null || string.equals("")) {
            return "";
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date time = null;
        try {
            time = format.parse(string);
//            time= format.parse(format.format(new Date(string)));
        } catch (ParseException e) {
//            MyLog.e("--------" + e);
            e.printStackTrace();
        }

        return format.format(time);
    }

    public static String StringToDateHH() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH 时");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;

    }

    /**
     * 获得年
     *
     * @return
     */
    public static String StringToYear() {
        String timeStr;
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        Date time = null;
        time = new Date(System.currentTimeMillis());//获取当前时间
        timeStr = format.format(time);
        return timeStr;
    }

    /**
     * 获得年
     *
     * @return
     */
    public static String StringToYearLastTwo() {
        String timeStr;
        SimpleDateFormat format = new SimpleDateFormat("yy");
        Date time = null;
        time = new Date(System.currentTimeMillis());//获取当前时间
        timeStr = format.format(time);
        return timeStr;
    }
    /**
     * 月
     *
     * @return
     */
    public static String StringToMonth() {
        String timeStr;
        SimpleDateFormat format = new SimpleDateFormat("MM");
        Date time = null;
        time = new Date(System.currentTimeMillis());//获取当前时间
        timeStr = format.format(time);
        return timeStr;
    }

    /**
     * 日
     *
     * @return
     */
    public static String StringToDay() {
        String timeStr;
        SimpleDateFormat format = new SimpleDateFormat("dd");
        Date time = null;
        time = new Date(System.currentTimeMillis());//获取当前时间
        timeStr = format.format(time);
        return timeStr;
    }

    static Date startDate = null;

    public static String FFTime(boolean start, boolean end) {

        if (start) {
            startDate = new Date(System.currentTimeMillis());
        }
        //在收到设备返回数据之后添加如下语句：
        if (end) {
            Date endDate = new Date(System.currentTimeMillis());
            long diff = endDate.getTime() - startDate.getTime();
            return diff + "";
        }
        return "开始：" + startDate;
    }

    public static String getDateBefore(String datetime) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date d = df.parse(datetime);
            long current = System.currentTimeMillis();
            long diff = current - d.getTime();
            long days = diff / (1000 * 60 * 60 * 24);

            if (days > 0) {
                return days + "天前";
            }
            long hours = (diff - days * (1000 * 60 * 60 * 24))
                    / (1000 * 60 * 60);
            if (hours > 0) {
                return hours + "小时前";
            }
            long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours
                    * (1000 * 60 * 60))
                    / (1000 * 60);

            if (minutes > 0) {
                return minutes + "分钟前";
            }

            if (diff / 1000 > 0) {
                return (diff / 1000) + "秒前";
            }

            return df.format(current) + "";

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    public static String formatDuring(long mss) {
        long days = mss / (24);
        long hours = (mss % 24);
        return days + " 天 " + hours + " 小时 ";
    }

    public static String getDateBeforeInt(String datetime) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date d = df.parse(datetime);
            long current = System.currentTimeMillis();
            long diff = current - d.getTime();
            long days = diff / (1000 * 60 * 60 * 24);

            if (days > 0) {
                return days + "天前";
            }
            long hours = (diff - days * (1000 * 60 * 60 * 24))
                    / (1000 * 60 * 60);
            if (hours > 0) {
                return hours + "小时前";
            }
            long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours
                    * (1000 * 60 * 60))
                    / (1000 * 60);

            if (minutes > 0) {
                return minutes + "分钟前";
            }

            if (diff / 1000 > 0) {
                return (diff / 1000) + "秒前";
            }

            return df.format(current) + "";

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

}
